package org.promote.hotspot.client.core.server;

import com.google.common.eventbus.Subscribe;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.promote.hotspot.client.netty.ChannelInactiveEvent;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 订阅者
 *
 * @author enping.jep
 * @date 2023/11/17 14:50
 **/
@Slf4j
public class ServerInfoChangeSubscriber {

    /**
     * 监听worker信息变动
     * 连接新的服务器，关闭不在列表中的连接
     */
    @Subscribe
    public void connectAll(ServerInfoChangeEvent event) {
        List<String> addresses = event.getAddresses();
        if (addresses == null) {
            addresses = new ArrayList<>();
        }
        ServerInfoHolder.mergeAndConnectNew(addresses);
    }

    /**
     * 当client与worker的连接断开后，删除
     */
    @Subscribe
    public void channelInactive(ChannelInactiveEvent inactiveEvent) {
        //获取断线的channel
        Channel channel = inactiveEvent.getChannel();
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        String address = socketAddress.getHostName() + ":" + socketAddress.getPort();
        log.warn(String.format("this channel is inactive : %s trying to remove this connection", socketAddress), getClass());
        ServerInfoHolder.dealChannelInactive(address);
    }
}
